import React, {useState, useEffect, useRef, useLayoutEffect} from "react";
import {useNavigation} from "@react-navigation/native";
import StatusBarCtl from "../../utils/StatusBarCtl";
import {FlatList, SafeAreaView, Text, TouchableOpacity, View} from "react-native";
import SearchInput from "../../components/SearchInput";
import {Colors, Size} from "../../styles";
import ApiService from "../../utils/ApiService";
import Swiper from "react-native-swiper";
import FastImage from "react-native-fast-image";
import {LoadingView} from "react-native-gzdsx-elements";
import ProductListItem from "./components/ProductListItem";
import {Icon} from "react-native-elements";

const SwiperView = () => {
    const [loading, setLoading] = useState(true);
    const [images, setImages] = useState([]);
    useEffect(() => {
        fetchData();
        return () => {

        };
    }, []);

    const fetchData = () => {
        ApiService.get('/blocks/1').then(response => {
            setImages(response.result.items);
            setLoading(false);
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            setLoading(false);
        });
    }

    const containerSize = {
        width: Size.screenWidth,
        height: Size.screenWidth * 0.5,
        backgroundColor: '#f9f9f9'
    };

    if (loading) {
        return (
            <View style={[containerSize, {justContent: 'center', alignItems: 'center'}]}>
                <LoadingView/>
            </View>
        )
    }

    return (
        <Swiper style={containerSize} dotColor={"#ccc"} autoplay>
            {
                images.map((img, index) => (
                    <TouchableOpacity
                        activeOpacity={1}
                        key={index.toString()}
                        onPress={() => {

                        }}
                    >
                        <FastImage
                            source={{uri: img.image}}
                            style={containerSize}
                        />
                    </TouchableOpacity>
                ))
            }
        </Swiper>
    );
}

const CategoryView = () => {
    const navigation = useNavigation();

    const [loading, setLoading] = useState(true);
    const [categories, setCategories] = useState([]);

    useEffect(() => {
        ApiService.get('/categories?taxonomy=product').then(response => {
            //console.log('categories:', response.result);
            setCategories(response.result.items);
            setLoading(false);
        });
        return () => {

        };
    }, []);

    return (
        <View style={{
            paddingTop: 10,
            paddingBottom: 10,
            flexDirection: 'row',
            flexWrap: 'wrap',
            backgroundColor: '#fff'
        }}>
            {
                categories.map((cate, index) => (
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{
                            alignContent: 'center',
                            alignItems: 'center',
                            width: Size.screenWidth * 0.25,
                            marginTop: 8,
                            marginBottom: 8
                        }}
                        onPress={() => {
                            navigation.navigate('product-list', {cate_id: cate.cate_id});
                        }}
                        key={'key2' + index.toString()}
                    >
                        <FastImage
                            source={{uri: cate.image}}
                            style={{
                                width: 50,
                                height: 50
                            }}
                        />
                        <Text style={{
                            fontSize: 14,
                            color: '#333',
                            textAlign: 'center',
                            marginTop: 5
                        }}>{cate.name}</Text>
                    </TouchableOpacity>
                ))
            }
        </View>
    );
}

const EcomHome = () => {
    const navigation = useNavigation();

    const [loading, setLoading] = useState(true);
    const [products, setProducts] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);

    const offset = useRef(0);
    const requesting = useRef(false);

    useLayoutEffect(() => {
        navigation.setOptions({
            headerShown: false
        });
        return navigation.addListener('focus', () => {
            StatusBarCtl.setToLightStyle();
        });
    }, [navigation]);

    useEffect(() => {
        fetchProducts();
    }, []);

    useEffect(() => {
        if (refreshing) {
            offset.current = 0;
            fetchProducts();
        }
    }, [refreshing]);

    useEffect(() => {
        if (loadingMore) {
            offset.current += 20;
            fetchProducts();
        }
    }, [loadingMore]);

    const onRefresh = () => {
        if (requesting.current) {
            return false;
        }
        setRefreshing(true);
    }

    const onEndReached = () => {
        if (requesting.current) {
            return false;
        }
        setLoadingMore(true);
    }

    const fetchProducts = () => {
        requesting.current = true;
        ApiService.get('/products', {
            params: {
                offset: offset.current,
                limit: 20,
                sort: 'time-desc'
            }
        }).then(response => {
            const {items} = response.result;
            if (loadingMore) {
                setProducts(products.concat(items));
            } else {
                setProducts(items);
            }
        }).finally(() => {
            requesting.current = false;
            setLoading(false);
            setRefreshing(false);
            setLoadingMore(false);
        });
    }

    return (
        <View style={{flex: 1}}>
            <SafeAreaView style={{backgroundColor: Colors.primary}}>
                <View style={{flexDirection: 'row', columnGap: 5}}>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{justifyContent: 'center', paddingLeft: 15}}
                    >
                        <Icon name={'line-scan'} type={'material-community'} color={'#fff'} size={26}/>
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{paddingVertical: 10, flex: 1}}
                    >
                        <SearchInput
                            placeholder={'请输入关键字搜索'}
                            editable={false}
                            pointerEvents={'none'}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{justifyContent: 'center', paddingRight: 15}}
                    >
                        <Icon name={'more-horiz'} color={'#fff'} size={26}/>
                    </TouchableOpacity>
                </View>
            </SafeAreaView>
            <FlatList
                data={products}
                renderItem={data => (
                    <ProductListItem
                        product={data.item}
                    />
                )}
                keyExtractor={(item, index) => index.toString()}
                numColumns={2}
                ListHeaderComponent={
                    <View>
                        <SwiperView/>
                        <CategoryView/>
                    </View>
                }
                ListEmptyComponent={
                    loading ? <LoadingView/> : null
                }
                columnWrapperStyle={{
                    paddingHorizontal: 5,
                    paddingVertical: 5
                }}
                refreshing={refreshing}
                onRefresh={onRefresh}
                onEndReachedThreshold={.2}
                onEndReached={onEndReached}
            />
        </View>
    )
}

export default EcomHome;
